package com.huluobo.hyj.hyjmodel.widet

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import com.huluobo.hyj.hyjmodel.R
import com.huluobo.hyj.hyjmodel.adapter.EMCallbackAdapter
import com.huluobo.hyj.hyjmodel.data.AddFriendItem
import com.hyphenate.chat.EMClient
import kotlinx.android.synthetic.main.view_add_friend_item.view.*
import org.jetbrains.anko.runOnUiThread
import org.jetbrains.anko.toast

/**
 *@author : USER
 *@date : 2020/9/17 15:21
 *@params :
 *@description:
 */
class AddFriendListitemView(context:Context?,attrs:AttributeSet?=null)
    :RelativeLayout(context,attrs) {
    fun bindView(addFriendItem: AddFriendItem){
        //设置按钮的选择(添加之后就不能点击了将按钮设置成灰色)
        if(addFriendItem.isAdded){
            add.isEnabled = false
            add.text = context.getString(R.string.already_added)
        }else{
            add.isEnabled = true
            add.text = context.getString(R.string.add)
        }


        userName.text = addFriendItem.username
        timestamp.text = addFriendItem.timestamp

        //点击事件
        add.setOnClickListener { addFriend(addFriendItem.username) }
    }

    private fun addFriend(username: String) {
        EMClient.getInstance().contactManager().aysncAddContact(username,null,object : EMCallbackAdapter(){
            override fun onSuccess() {
                context.runOnUiThread { toast("添加成功") }
            }

            override fun onError(code: Int, error: String?) {
                context.runOnUiThread { toast("添加失败") }
            }
        })
    }

    //初始化
    init {
        //加载item布局
        View.inflate(context,R.layout.view_add_friend_item,this)
    }
}